<?php
/**
 * 自定义行为过滤器
 */

namespace backend\filter;


use yii\base\ActionFilter;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\helpers\VarDumper;
use yii\web\HttpException;

class AccessFilter extends ActionFilter
{
    public function beforeAction($action)
    {
        //判断当前用户是否拥有该操作的访问权限
        if(!\Yii::$app->user->can($action->uniqueId)){

            //判断当前用户是否是游客,如果是,跳转到登录页面
            if(\Yii::$app->user->isGuest){
                return $action->controller->redirect(\Yii::$app->user->loginUrl);
            }

            if(\Yii::$app->request->isAjax){
                return '304';
            }
            //没有权限,抛出一个403 forbidden 异常
            throw new HttpException(304,'对不起,你没有该操作的权限');

            return true;

        }

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
}